#include "time_filter.h"

#include <trantor/utils/Date.h>
#include <trantor/utils/Logger.h>

#define VDate "visitDate"

void TimeFilter::doFilter(const HttpRequestPtr &req,
		FilterCallback &&cb,
		FilterChainCallback &&ccb) {
	trantor::Date now = trantor::Date::date();

	if (req->session() != nullptr) {
		if (req->session()->find(VDate)) {
			auto lastDate = req->session()->get<trantor::Date>(VDate);
			LOG_TRACE << "last:" << lastDate.toFormattedString(false);
			req->session()->modify<trantor::Date>(VDate,
					[now](trantor::Date &vdate) {
						vdate = now;
					});
			if (now > lastDate.after(2)) {
				ccb();
				return;
			} else {
				Json::Value json;
				json["code"] = 0;
				json["data"] = "wait 2 seconds";
				auto res = HttpResponse::newHttpJsonResponse(json);
				cb(res);
				return;
			}
		}
		LOG_TRACE << "first access,insert visitDate";
		req->session()->insert(VDate, now);
	}
	ccb();
}